package com.roper.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.roper.yygh.hosp.repository.DepartmentRepository;
import com.roper.yygh.hosp.service.DepartmentService;
import com.roper.yygh.model.hosp.Department;
import com.roper.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * Description:
 * Date:      2021/11/22 19:05
 * author:    LPH
 * version:   V1.0
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    // 保存科室信息
    @Override
    public void save(Map<String, Object> map) {
        // 先讲map转换为对象
        String mapString = JSONObject.toJSONString(map);
        Department department = JSONObject.parseObject(mapString, Department.class);
        Date date = new Date();

        // 根据医院编号和科室编号进行判断是否存在
        Department departmentExist = departmentRepository.getDepartmentByDepcodeAndHoscode(department.getDepcode(), department.getHoscode());
        // 更新
        if(departmentExist != null) {
            department.setUpdateTime(date);
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }else {
            // 插入
            department.setCreateTime(date);
            department.setUpdateTime(date);
            department.setIsDeleted(0);
            departmentRepository.insert(department);
        }
    }

    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        Pageable pageable = PageRequest.of(page, limit);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Department> example = Example.of(department, matcher);
        return departmentRepository.findAll(example, pageable);
    }

    @Override
    public void removeDepartment(String hosCode, String depcode) {
        Department department = departmentRepository.getDepartmentByDepcodeAndHoscode(depcode, hosCode);
        if(department != null) {
            departmentRepository.deleteById(department.getId());
        }
    }


}
